package org.oos.lists;

import java.util.AbstractList;
import java.util.Comparator;
import java.util.List;

import org.oos.OOS4Java;
import org.oos.atom.entries.ReviewEntry;
import org.oos.dao.lists.impl.RestoredDynamicList;
import org.oos.model.Review;
import org.oos.util.Cache;

public class ReviewList extends AbstractList<Review> implements RestorableList<ReviewEntry> {

	private OOS4Java oos4Java;
	private List<ReviewEntry> list;
	private Cache<ReviewEntry, Review> cache = new Cache<ReviewEntry, Review>();

	public ReviewList(OOS4Java oos4Java, List<ReviewEntry> list) {
		this.oos4Java = oos4Java;
		this.list = list;
	}

	@Override
	public Review get(int location) {
		ReviewEntry entry = list.get(location);
		Review result;
		if (cache.containsKey(entry)) {
			result = cache.get(entry);
		} else {
			result = new Review(oos4Java, list.get(location));
			cache.put(entry, result);
		}
		return result;
	}
	
	public Review find(String userSlug, String siteSlug) {
		for (Review review : this) {
			if (review.getSite().getSlug().equals(siteSlug)
					&& review.getAuthor().getSlug().equals(userSlug)) {
				return review;
			}
		}
		return null;
	}
	
	@Override
	public int size() {
		return list.size();
	}

	@Override
	public boolean add(Review review) {
		return list.add((ReviewEntry)review.getEntry());
	}

	public Review update(Review review) {
		int index = list.indexOf((ReviewEntry)review.getEntry());
		return this.set(index, review);
	}

	@Override
	public Review set(int index, Review review) {
		ReviewEntry entry = list.set(index, review.getEntry());
		return new Review(oos4Java, entry);
	}

	@Override
	public Review remove(int index) {
		ReviewEntry entry = list.remove(index);
		return new Review(oos4Java, entry);
	}

	@Override
	public boolean remove(Object o) {
		if (o instanceof Review) {
			Review review = (Review) o;
			return list.remove(review.getEntry());
		} else {
			return false;
		}
	}
	
	@Override
	public void clear() {
		cache.clear();
		super.clear();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void sort(Comparator<ReviewEntry> comparator) {
		if (isRestored()) {
			((RestoredDynamicList) this.list).sort(comparator);
		}
	}
	
	@Override
	public void sort() {
		sort(new Comparator<ReviewEntry>() {
			@Override
			public int compare(ReviewEntry r1, ReviewEntry r2) {
				String name1 = r1.getTitle().getValue().toLowerCase();
				String name2 = r2.getTitle().getValue().toLowerCase();
				return name1.compareTo(name2);
			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isRestored() {
		return this.list instanceof RestoredDynamicList;
	}
}
